<?php
class Admin_NewsController extends Zend_Controller_Action{
	public function indexAction(){
		$news = new Application_Model_NewsMapper();
		$page = (int) $this->_getParam('page', 1);
		$paginator = Zend_Paginator::factory($news->fetchAll());
		$paginator	-> setItemCountPerPage(10)
					-> setCurrentPageNumber($page)
					-> setPageRange(3);
		$this->view->entries = $paginator;
	}
	public function addAction(){
		$request = $this->getRequest();
		$form = new Admin_Form_News();
		
		if($this->getRequest()->isPost()){
			if($form->isValid($request->getPost())){
				$values = $form->getValues();
				$mapper = new Application_Model_NewsMapper();
				$news = new Application_Model_News();
				$news 	->setAuthor(Zend_Auth::getInstance()->getIdentity()->id)
						->setText($values['text'])
						->setTitle($values['title']);
				$mapper ->save($news);
				
				$this->_helper->redirector('index');
			}else{
				$this->view->form = $form;
				$errors = $form->getMessages();
				$messages = array();
				foreach ($errors as $err) {
					foreach($err as $mess){
						$messages[]=$mess;
					}
				}
				$this->view->errors = $messages;
			}
		}else{
			$this->view->form = $form;
		}
	}
	public function editAction(){
		$request = $this->getRequest();
		$form = new Admin_Form_News();
		$mapper = new Application_Model_NewsMapper();
		$id = (int) $this->_getParam('news', null);
		
		if($request->isPost()){
			if($form->isValid($request->getPost())){
				$values = $form->getValues();
				$mapper = new Application_Model_NewsMapper();
				$news = new Application_Model_News();
				$news 	->setId($values['id'])
						->setText($values['text'])
						->setTitle($values['title']);
				$mapper ->save($news);
				
				$this->_helper->redirector('index');
			}else{
				$this->view->form = $form;
				$errors = $form->getMessages();
				$messages = array();
				foreach ($errors as $err) {
					foreach($err as $mess){
						$messages[]=$mess;
					}
				}
				$this->view->errors = $messages;
			}
		}else{
			if($id>0){
				$dbTable = new Application_Model_DbTable_News();
				$form->populate($dbTable->find($id)->current()->toArray());
			}else{
				
			}
			$this->view->form = $form;
		}
	}
	public function deleteAction(){
		$request = $this->getRequest();
		$id = (int) $this->_getParam('news', null);
		$newsMap = new Application_Model_NewsMapper();
		if($id>0){
			$newsMap->delete($id);
			$this->_helper->redirector('index');
		}else{
			$this->_helper->redirector('deny','error');
		}
	}
}